package com.gaojiawei.multiThread12_ThreadPoolExecutor;

import java.util.concurrent.*;

/**
 * create thread pool and deal task having or not having result
 */
public class L01_ThreadPoolDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //create thread pool
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(2, 5, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<>(5),
                new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable r) {
                        Thread thread = new Thread(r);
                        thread.setName("test thread pool executor");
                        return thread;
                    }
                }, new MyRejectExecution());

        //thread pool deal with task having no result
        threadPool.execute(()->{
            System.out.println("deal with a task having no result");
        });

        //thread pool deal with task having result
        Future<Object> submit = threadPool.submit((Callable<Object>) () -> "deal with task having no result");

        Object o = submit.get();
        System.out.println(o);

        //if thread pool is local varible please shutdown
        threadPool.shutdown();

    }

    public static class MyRejectExecution implements RejectedExecutionHandler{

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            System.out.println("根据自己的业务情况，决定编写自己的代码");
        }
    }
}
